<?php
class UploadTool
{
    static $type = array('jpg','gif','png','bmp');
    static $dir  = UPLOAD_PATH;


    /**
     *
     * @access public
     * @static
     * @param  string $file
     * @return array|bool
     */
    public static function doImages($file)
    {
        $ym     = date("Ym");
        $ndir   = self::$dir.$ym.'/';
        imkdir($ndir) && self::$dir = $ndir;
        $filename = self::doUpload($file);

        if ($filename) {
           $urlpath = STATIC_PATH.'/upload/'.$ym.'/';
           return array(
               'path'  => $ndir.$filename,
               'url'   => $urlpath.$filename
           );
        } else {
            return false;
        }

    }

    public static function doAttr($file)
    {
        $ym     = date("Ym");
        $ndir   = self::$dir.$ym.'/';
        imkdir($ndir) && self::$dir = $ndir;
        $filename = self::doUpload($file, false);

        if ($filename) {
            $urlpath = STATIC_PATH.'/upload/'.$ym.'/';
            return array(
                'path'  => $ndir.$filename,
                'url'   => $urlpath.$filename,
                'filename'  => $_FILES[$file]['name']
            );
        } else {
            return false;
        }
    }

    /**
     *
     * 上传方法
     *
     * @static
     * @access private
     * @param  $upload
     * @param  string $dir
     * @param  string $img_name
     * @return bool|string
     */
    private static function doUpload($upload, $isValid=true)
    {
        if ($_FILES[$upload]) {
            $file       = $_FILES[$upload];
            $filename   = self::getNewName($file['name']);
            $type       = self::$type;
            if (!$isValid || in_array(self::getFileSuffix($file['name']), $type)) {
                if (move_uploaded_file($file['tmp_name'], self::$dir.$filename)) {
                    return $filename;
                }
            } else {
                return false;
            }
        }
    }

    static function getNewName($filename = '')
    {
        $arr  = explode('.',$filename);
        $name = time().rand(100000,999999);
        return $name.'.'.$arr[count($arr)-1];
    }

    private static function getFileSuffix($file)
    {
        return end(explode('.',$file));
    }
}
